package weaver.batchchanges.cmd;

import com.alibaba.nacos.client.utils.StringUtils;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import weaver.conn.RecordSet;
import weaver.batchchanges.bean.BatchTasksChangesTempBean;
import weaver.batchchanges.bean.BatchTasksChangesGlobalData;
import weaver.batchchanges.util.DataConvertUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 修改BatchTasksChangesTempData的cmd
 */
public class UpdateBatchTasksChangesTempDataCmd extends AbstractCommonCommand<Boolean> {


    private List<String> ids;//存放用于同时更新多条数据的id

    public UpdateBatchTasksChangesTempDataCmd(BatchTasksChangesTempBean batchTasksChangesTempBean) {
        this.params = DataConvertUtil.convertToMap(batchTasksChangesTempBean);

    }

    public UpdateBatchTasksChangesTempDataCmd(Map map, List<String> ids) {
        this.params = map;
        this.ids = ids;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Boolean execute(CommandContext commandContext) {
        RecordSet rs = new RecordSet();

//        String sql = "update "+BatchTasksChangesGlobalData.TEMPORARY_TASK_LEDGER_TABLE_NAME+ " SET ";
        StringBuilder sql = new StringBuilder("update " + BatchTasksChangesGlobalData.TEMPORARY_TASK_LEDGER_TABLE_NAME + " SET ");

        Set<String> keySet = this.params.keySet();
        List<Object> values = new ArrayList<>();
        keySet.forEach(key -> {
            if (StringUtils.isNotEmpty(key) && !key.equals("touchpointbh") && !key.equals("id") && this.params.get(key) != null) {
                sql.append(key + " = ? ");
                values.add(this.params.get(key));
            }
        });
        //拼接需要更新数据的ids
        sql.append(" where id in ( " + String.join(",", getIds()) + ")");
        boolean b = rs.executeUpdate(sql.toString(), values.toArray());
        return b;
    }


    /**
     * 获取需要更新数据的id列表
     *
     * @return
     */
    private List<String> getIds() {

        if (ids == null) {
            return new ArrayList<String>() {{
                add(String.valueOf(params.get("id")));
            }};
        }
        return ids;
    }
}
